# -*- coding: utf-8 -*-
from os import path
from json import loads
from shutil import rmtree
from urllib import urlopen
from xbmcaddon import Addon
from xbmcplugin import endOfDirectory, addDirectoryItem
from xbmcgui import ListItem, Dialog
from xbmcvfs import listdir, mkdirs
from xbmc import translatePath, executebuiltin, getInfoLabel, Player, sleep, log
import sys

reload(sys)
sys.setdefaultencoding('utf8')

__addon__ = Addon()
__scriptid__ = __addon__.getAddonInfo('id')
__temp__ = unicode(translatePath(__addon__.getAddonInfo('profile')), 'utf-8')
__subs__ = unicode(translatePath(path.join(__temp__, 'subs')), 'utf-8')
__language__ = __addon__.getLocalizedString

_token_ = __addon__.getSetting("customToken")


def Search(item):
    DEFAULT_TOKEN = "vXMvTf8eu4pfmAVmllp8OY6aYqVbeB4F"
    subtitles_list = []
    token = _token_ or DEFAULT_TOKEN
    extra_arg = ""
    if item['mansearch']:
        title = item['mansearchstr']
    else:
        title = item['title']
        extra_arg = "&no_muxer=1"
    
    url = 'http://api.assrt.net/v1/sub/search?token=%s&q=%s&xbmc=1%s' % (token, title, extra_arg)
    log(msg='url is %s' % url, level=1)
    socket = urlopen(url)
    data = socket.read()
    socket.close()
    result = loads(data)
    if result['status']:
        dialog = Dialog()
        if result['status'] == 30900 and token == DEFAULT_TOKEN:
            dialog.notification(u'公共API配额超限', '建议使用自定义密钥', 'info', 3000)
        else:
            dialog.notification(u'API请求失败', '%d: %s' % (result['status'], result['errmsg']), 'error', 3000)
        return
    for sub in result['sub']['subs']:
        _ = []
        for k in ('videoname', 'native_name'):
            if k in sub and sub[k]:
                _.append(sub[k])
        it = {"id":sub['id'],
                "filename": "/".join(_),
                "rating":str(int(sub['vote_score']) / 20),
                "language_name":"",
                "language_flag":""
               }
        if 'lang' in sub:
            ll = sub['lang']['langlist']
            if 'langchs' in ll or 'langcht' in ll or 'langdou' in ll:
                it.update({"language_name":"Chinese", "language_flag":'zh'})
            elif 'langeng' in ll:
                it.update({"language_name":"English", "language_flag":'en'})
            elif 'langjap' in ll:
                it.update({"language_name":"Japanese", "language_flag":'jp'})
            elif 'langkor' in ll:
                it.update({"language_name":"Korea", "language_flag":'kr'})
            elif 'langesp' in ll:
                it.update({"language_name":"Spanish", "language_flag":'es'})
            elif 'langfra' in ll:
                it.update({"language_name":"France", "language_flag":'fr'})
        subtitles_list.append(it)

    if subtitles_list:
        for it in subtitles_list:
            listitem = ListItem(label=it["language_name"],
                                  label2=it["filename"],
                                  iconImage=it["rating"],
                                  thumbnailImage=it["language_flag"]
                                  )
            listitem.setProperty("sync", "false")
            listitem.setProperty("hearing_imp", "false")
            url = "plugin://%s/?action=download&id=%s" % (__scriptid__, it["id"])
            addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)


def CheckSubList(files):
    list = []
    for subfile in files:
        if path.splitext(subfile)[1] in [".srt", ".ssa", ".ass", ".smi", ".sub"]:
            list.append(subfile)
    return list


def DownloadID(id):
    try: rmtree(__subs__)
    except: pass
    try: mkdirs(__subs__)
    except: pass
    subtitle_list = []
    url = 'http://assrt.net/download/%s/%s' % (id, 'XBMC.SUBTITLE')
    socket = urlopen(url)
    data = socket.read()
    socket.close()
    header = data[:4]
    if header == 'Rar!':
        zipext = ".rar"
    else:
        zipext = ".zip"
    zipname = 'SUBPACK%s' % (zipext)
    zip = path.join(__subs__, zipname)
    with open(zip, "wb") as subFile:
        subFile.write(data)
    subFile.close()
    sleep(500)
    executebuiltin(('XBMC.Extract("%s","%s")' % (zip, __subs__,)).encode('utf-8'), True)
    subPath = __subs__
    dirs, files = listdir(subPath)
    list = CheckSubList(files)
    if not list and len(dirs) > 0:
        dialog = Dialog()
        sel = dialog.select(__language__(32002), dirs)
        if sel != -1:
            subPath = path.join(subPath, dirs[sel].decode('utf-8'))
        else:
            subPath = path.join(subPath, dirs[0].decode('utf-8'))
        dirs, files = listdir(subPath)
        list = CheckSubList(files)
    filename = ''
    if len(list) > 0:
        dialog = Dialog()
        sel = dialog.select(__language__(32006), list)
        if sel != -1:
            filename = list[sel].decode('utf-8')
    if filename:
        filepath = path.join(subPath, filename)
        subtitle_list.append(filepath)
    return subtitle_list


def get_params():
    param = []
    paramstring = sys.argv[2]
    if len(paramstring) >= 2:
        params = paramstring
        cleanedparams = params.replace('?', '')
        if (params[len(params) - 1] == '/'):
            params = params[0:len(params) - 2]
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]

    return param


params = get_params()
if params['action'] == 'search' or params['action'] == 'manualsearch':
    item = {}
    item['mansearch'] = False
    item['title'] = getInfoLabel("VideoPlayer.Title")  # try to get original title

    if 'searchstring' in params:
        item['mansearch'] = True
        item['mansearchstr'] = params['searchstring']

    Search(item)

elif params['action'] == 'download':
    subs = DownloadID(params["id"])
    for sub in subs:
        listitem = ListItem(label=sub)
        addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False)

endOfDirectory(int(sys.argv[1]))
